<template>
  <ArtLayouts>
    <!-- 顶栏、水平/混合菜单 -->
    <ArtHeaderBar :driverInfo="driverInfo" />
    <!-- 左侧/双列菜单 -->
    <ArtSidebarMenu :driverInfo="driverInfo" />
    <!-- 页面内容 -->
    <ArtPageContent />
    <!-- 设置面板 -->
    <ArtSettingsPanel />
    <!-- 全局搜索 -->
    <ArtGlobalSearch />
    <!-- 屏幕锁定 -->
    <ArtScreenLock />
    <!-- 聊天窗口 -->
    <ArtChatWindow />
    <!-- 礼花效果 -->
    <ArtFireworksEffect />
    <!-- 水印效果 -->
    <ArtWatermark />
  </ArtLayouts>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store/modules/user'
import { getRoleCodeList } from '@/api/driverSchoolApi'
import { useMenuStore } from '@/store/modules/menu'
import type { AppRouteRecord } from '@/types/router'
import { BasicSetting } from '@/api/driverSchoolApi'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()

const allSelectRole = async () => {
  try {
    const roles: any = userStore.info?.roles?.join(',')
    const res = await getRoleCodeList({ codes: roles })
    const allowedIds = res?.data?.length ? res.data : []
    userStore.setRoleIds(allowedIds)
    const menuStore = useMenuStore()
    if (!Array.isArray(allowedIds) || allowedIds.length === 0) {
      menuStore.setMenuList([])
      router.push({ path: '@views/exception/404/index.vue', query: { isShow: 1 } })
      return
    }
    const originalMenu: AppRouteRecord[] = menuStore.getMenuList()
    const allowedSet = new Set(allowedIds.map((id: string | number) => String(id)))

    // 递归查找第一个有id且在allowedSet中的页面
    const findFirstAllowedMenu = (items: AppRouteRecord[]): AppRouteRecord | null => {
      for (const item of items) {
        if (item.id !== undefined && item.id !== null && allowedSet.has(String(item.id))) {
          // 如果有children，优先找子菜单
          if (item.children && item.children.length > 0) {
            const child = findFirstAllowedMenu(item.children)
            if (child) return child
          }
          return item
        } else if (item.children && item.children.length > 0) {
          const child = findFirstAllowedMenu(item.children)
          if (child) return child
        }
      }
      return null
    }

    // 只展示在 allowedIds 里的菜单（包括父级和子级），没有选中的菜单不会展示
    const filterByIds = (items: AppRouteRecord[]): AppRouteRecord[] => {
      return (items || []).reduce((acc: AppRouteRecord[], item) => {
        const children = item.children?.length ? item.children : []
        const filteredChildren = filterByIds(children)
        const hasId = item.id !== undefined && item.id !== null
        const idMatched = hasId ? allowedSet.has(String(item.id)) : false
        if (idMatched) {
          acc.push({ ...item, children: filteredChildren })
        } else if (filteredChildren.length > 0) {
          acc.push({ ...item, children: filteredChildren })
        }
        return acc
      }, [])
    }

    const filtered = filterByIds(originalMenu)
    menuStore.setMenuList(filtered)

    // 自动跳转到第一个有id且有权限的页面
    // const firstMenu = findFirstAllowedMenu(filtered)
    // if (firstMenu && firstMenu.path) {
    //   router.replace({ path: firstMenu.path })
    // }
  } catch (e) {
    console.error('获取菜单权限ID失败：', e)
  }
}
const driverInfo = ref()
const getData = async () => {
  const res = await BasicSetting()
  if (res.code === '00000') {
    driverInfo.value = res.data
  }
}
onMounted(() => {
  getData()
  allSelectRole()
})
</script>

<style lang="scss" scoped>
@use './style';
</style>
